package cn.akwangl.springbootdev.jackson.controller;

import cn.akwangl.springbootdev.Resource;
import cn.akwangl.springbootdev.annotion.ControllerLogs;
import cn.akwangl.springbootdev.jackson.vo.UserVO;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/jackson")
public class JacksonController {

    private static final Logger logger = LogManager.getLogger(JacksonController.class);

    private static Integer NUM = 200000;

    @Autowired
    private Resource resource;

    @GetMapping("/test")
    public Object jacksonTest() {
        Map<Object, Object> map = new HashMap<>();
        UserVO userVO = new UserVO("小明", 29, "男", new Date());
        userVO.setSex(null);
        ArrayList<Object> list = new ArrayList<>();
        map.put("date", userVO);
        map.put("list", list);
        return map;
    }

    @GetMapping("/test2")
    public Object jacksonTest2() throws Exception {
        UserVO userVO = new UserVO("小明", 29, "男", new Date());

        ObjectMapper mapper = new ObjectMapper();
        // 转JSON字符串
        String jsonStr = mapper.writeValueAsString(userVO);
        System.out.println("JSON转换的数据 => " + jsonStr);

        // JSON字符串转JavaBean
        UserVO userVO2 = mapper.readValue(jsonStr, UserVO.class);
        System.out.println("userVO2 数据 => " + userVO2.toString());
        return jsonStr;
    }

    @PostMapping("/test3")
    public Object jacksonTest3(@RequestBody @Validated UserVO userVO) {
        System.out.println("数据" + userVO);
        return userVO;
    }

    @GetMapping("/test4")
    @ControllerLogs(description = "Log 日志测试中...")
    public Object jacksonTest4(Integer num) {
        if (num != null) {
            JacksonController.NUM = num;
        }
        for (int i = 0; i < num; i++) {
            logger.debug("日志 debug" + this.resource);
            logger.info("日志 info" + this.resource);
            logger.error("日志 error" + this.resource);
        }
        return this.resource;
    }

}
